#!/usr/bin/env bash
echo $1  #旧图片路径
echo $2  #新图片路径
echo $3  #用来判断新图片1、2、3倍图是否使用
echo $4  #是否删除新照片，move_to为删除，copy_to为不删除
# 删除所有旧图片和对应的contents.json
oldDirectory=${1%/*}
newDirectory=${2%/*}
oldImageName=$(basename $1)
newImageName=$(basename $2)
echo $oldDirectory
echo $newDirectory
echo $oldImageName
echo $newImageName

function deleteAllFile()
{
  for file in `ls $oldDirectory`;
    do
      filePath=$1"/"$file
      rm -rf $filePath
      echo "remove"$filePath
    done
}

deleteAllFile $oldDirectory

content='{
  "images" : ['

#1倍图处理
if [[ -f $2 ]] && [[ $3 == *1* ]]; then
  #存在一倍图
  if [[ $4 == move_to ]]; then
    mv $2 $1
  else
    cp $2 $1
  fi

  content=$content'
    {
      "idiom" : "universal",
      "filename" : "'$oldImageName'",
      "scale" : "1x"
    }'
else
  content=$content'
    {
      "idiom" : "universal",
      "scale" : "1x"
    }'
fi

#2倍图处理
tmpPath=$newDirectory"/"${newImageName/./@2x.}
echo $tmpPath
if [[ -f  $tmpPath ]]  && [[ $3 == *2* ]]; then
  #存在2倍图
  if [[ $4 == move_to ]]; then
    mv $tmpPath $oldDirectory"/"${oldImageName/./@2x.}
  else
    cp $tmpPath $oldDirectory"/"${oldImageName/./@2x.}
  fi
  content=$content',
    {
      "idiom" : "universal",
      "filename" : "'${oldImageName/./@2x.}'",
      "scale" : "2x"
    }'
else
  content=$content',
    {
      "idiom" : "universal",
      "scale" : "2x"
    }'
fi

#3倍图处理
tmpPath=$newDirectory"/"${newImageName/./@3x.}
echo $tmpPath
if [[ -f $tmpPath ]] && [[ $3 == *3* ]]; then
  #存在3倍图
  if [[ $4 == move_to ]]; then
    mv $tmpPath $oldDirectory"/"${oldImageName/./@3x.}
  else
    cp $tmpPath $oldDirectory"/"${oldImageName/./@3x.}
  fi
  content=$content',
    {
      "idiom" : "universal",
      "filename" : "'${oldImageName/./@3x.}'",
      "scale" : "3x"
    }
  ],
  "info" : {
    "version" : 1,
    "author" : "xcode"
  }
}'
else
  content=$content',
    {
      "idiom" : "universal",
      "scale" : "3x"
    }
  ],
  "info" : {
    "version" : 1,
    "author" : "xcode"
  }
}'
fi
echo $content
echo $content > $oldDirectory"/Contents.json"
